<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-button 
              type="primary" 
              link 
              @click="goBack"
              style="margin-right: 16px"
            >
              <el-icon><ArrowLeft /></el-icon>
              返回
            </el-button>
            <span>试卷：{{ paperName }}</span>
          </div>
          <el-button type="primary" @click="handleAddQuestion">添加题目</el-button>
        </div>
      </template>
      
      <el-table 
        v-loading="loading"
        :data="questionList" 
        style="width: 100%"
      >
        <el-table-column prop="sort" label="题号" width="80" />
        <el-table-column prop="type" label="题型" width="120" />
        <el-table-column prop="title" label="题目内容" show-overflow-tooltip />
        <el-table-column prop="score" label="分值" width="80" />
        <el-table-column prop="analysis" label="解析" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tooltip
              effect="dark"
              placement="top"
              :content="row.analysis || '暂无解析'"
            >
              <span>{{ row.analysis || '暂无解析' }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 题目编辑对话框 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="60%"
      >
        <el-form ref="questionForm" :model="questionForm" :rules="rules" label-width="100px">
          <el-form-item label="题型" prop="type">
            <el-select 
              v-model="questionForm.type"
              :disabled="!!currentId"
            >
              <el-option label="单选" value="单选" />
              <el-option label="多选" value="多选" />
              <el-option label="填空题" value="填空题" />
              <el-option label="简答题" value="简答题" />
              <el-option label="论述题" value="论述题" />
            </el-select>
            <div v-if="currentId" class="type-hint">题型在编辑时不可更改</div>
          </el-form-item>
          
          <el-form-item label="题目内容" prop="title">
            <el-input
              v-model="questionForm.title"
              type="textarea"
              rows="4"
            />
          </el-form-item>

          <!-- 选择题选项 -->
          <template v-if="['单选', '多选'].includes(questionForm.type)">
            <el-form-item label="选项" prop="options">
              <div v-for="(value, key) in questionForm.options" :key="key" class="option-item">
                <span class="option-label">{{ key.toUpperCase() }}.</span>
                <el-input v-model="questionForm.options[key]" />
                <el-radio 
                  v-if="questionForm.type === '单选'"
                  v-model="questionForm.answer"
                  :label="key.toUpperCase()"
                >正确答案</el-radio>
                <el-checkbox
                  v-else
                  v-model="questionForm.multiAnswer[key]"
                >正确答案</el-checkbox>
                <el-button type="danger" link @click="removeOption(key)">删除</el-button>
              </div>
              <div class="option-actions">
                <el-button 
                  type="primary" 
                  link 
                  @click="addOption"
                  :disabled="Object.keys(questionForm.options).length >= 8"
                >
                  添加选项
                </el-button>
              </div>
            </el-form-item>
            
            <!-- 添加解析输入框 -->
            <el-form-item label="解析" prop="analysis">
              <el-input
                v-model="questionForm.analysis"
                type="textarea"
                rows="4"
                placeholder="请输入题目解析"
              />
            </el-form-item>
          </template>

          <!-- 填空题和简答题的答案 -->
          <template v-if="['填空题', '简答题'].includes(questionForm.type)">
            <el-form-item label="参考答案" prop="analysis">
              <el-input
                v-model="questionForm.analysis"
                type="textarea"
                rows="4"
                placeholder="请输入参考答案"
              />
            </el-form-item>
          </template>

          <!-- 论述题的答案 -->
          <template v-if="questionForm.type === '论述题'">
            <el-form-item label="参考答案" prop="analysis">
              <el-input
                v-model="questionForm.analysis"
                type="textarea"
                rows="6"
                placeholder="请输入参考答案"
              />
            </el-form-item>
          </template>

          <el-form-item label="分值" prop="score">
            <el-input-number v-model="questionForm.score" :min="0" />
          </el-form-item>

          <el-form-item label="题号" prop="sort">
            <el-input-number v-model="questionForm.sort" :min="1" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { getQuestionList, addQuestion, updateQuestion, deleteQuestion } from '@/api/paper/question'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'

export default {
  name: 'PaperQuestions',
  components: {
    ArrowLeft
  },
  data() {
    return {
      paperId: undefined,
      paperName: '',
      questionList: [],
      questionTypeMap: {
        'single_choice': '单选题',
        'multiple_choice': '多选题',
        'fill_in_the_blank': '填空题',
        'short_answer': '简答题',
        'essay': '论述题'
      },
      dialogVisible: false,
      dialogTitle: '',
      questionForm: {
        type: '',
        title: '',
        options: {
          a: '',
          b: '',
          c: '',
          d: '',
          e: '',
          f: '',
          g: '',
          h: ''
        },
        answer: '',
        multiAnswer: {},
        analysis: '',
        score: 0,
        sort: 1,
        testPaperId: undefined
      },
      rules: {
        type: [{ required: true, message: '请选择题型', trigger: 'change' }],
        title: [{ required: true, message: '请输入题目内容', trigger: 'blur' }],
        answer: [{ required: true, message: '请输答案', trigger: 'blur' }],
        score: [{ required: true, message: '请输入分值', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入题号', trigger: 'blur' }]
      },
      loading: false,
      currentId: undefined,
    }
  },
  created() {
    const { paperId, paperName } = this.$route.query
    this.paperId = paperId
    this.paperName = paperName
    this.getList()
  },
  methods: {
    // 获取题目列表
    async getList() {
      try {
        this.loading = true
        const res = await getQuestionList(this.paperId)
        this.questionList = res.data
      } catch (error) {
        console.error('获取题目列表失败:', error)
        ElMessage.error('获取题目列表失败')
      } finally {
        this.loading = false
      }
    },
    
    handleAddQuestion() {
      this.dialogVisible = true
      this.dialogTitle = '添加题目'
      this.currentId = undefined
      this.resetQuestionForm()
    },
    
    handleEdit(row) {
      this.dialogVisible = true
      this.dialogTitle = '编辑题目'
      this.currentId = row.id
      
      const formData = {
        type: row.type,
        title: row.title,
        score: row.score,
        sort: row.sort,
        testPaperId: row.testPaperId
      }

      if (['单选', '多选'].includes(row.type)) {
        const options = this.parseOptions(row.options)
        formData.options = options
        formData.answer = row.answer

        if (row.type === '多选') {
          const multiAnswer = {}
          const answers = (row.answer || '').split(',')
          answers.forEach(ans => {
            multiAnswer[ans.toLowerCase()] = true
          })
          formData.multiAnswer = multiAnswer
        }
      } else if (row.type === '论述题') {
        formData.analysis = row.analysis || row.answer
        formData.answer = row.analysis || row.answer
      } else {
        formData.answer = row.answer
        formData.analysis = row.analysis
      }

      this.questionForm = formData
    },
    
    handleDelete(row) {
      ElMessageBox.confirm('确认要删除该题目吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteQuestion(row.id)
          ElMessage.success('删除成功')
          this.getList()
        } catch (error) {
          console.error('删除题目失败:', error)
          ElMessage.error('删除题目失败')
        }
      })
    },
    
    resetQuestionForm() {
      this.questionForm = {
        type: '',
        title: '',
        options: {
          a: '',
          b: '',
          c: '',
          d: ''  // 默认只显示4个选项
        },
        answer: '',
        multiAnswer: {
          a: false,
          b: false,
          c: false,
          d: false
        },
        analysis: '',
        score: 0,
        sort: 1,
        testPaperId: undefined
      }
    },

    // 处理选择题选项的字符串转换为对象
    parseOptions(optionsStr) {
      try {
        return JSON.parse(optionsStr || '{}')
      } catch (e) {
        console.error('项解析失败:', e)
        return {}
      }
    },

    async handleSave() {
      this.$refs['questionForm'].validate(async (valid) => {
        if (valid) {
          try {
            // 构造符合后端CTestPaperInfo格式的数据
            const data = {
              id: this.currentId, // 编辑时传id
              title: this.questionForm.title,
              type: this.questionForm.type,
              score: this.questionForm.score,
              sort: this.questionForm.sort,
              testPaperId: this.paperId,
              analysis: this.questionForm.analysis || '',
              answer: '',
              options: '{}'
            }

            // 数据验证
            if (data.score <= 0) {
              ElMessage.warning('分值必须大于0')
              return
            }

            // 处理不同题型的数据
            if (['单选', '多选'].includes(data.type)) {
              const optionsCount = Object.values(this.questionForm.options).filter(v => v).length
              if (optionsCount < 2) {
                ElMessage.warning('选择题至少需要2个选项')
                return
              }
              
              if (data.type === '单选' && !this.questionForm.answer) {
                ElMessage.warning('请选择正确答案')
                return
              }
              
              if (data.type === '多选') {
                const selectedAnswers = Object.entries(this.questionForm.multiAnswer)
                  .filter(([_, selected]) => selected)
                  .map(([key]) => key.toUpperCase())
                
                if (selectedAnswers.length === 0) {
                  ElMessage.warning('请至少选择一个正确答案')
                  return
                }
                
                data.answer = selectedAnswers.join(',')
              } else {
                data.answer = this.questionForm.answer
              }
              
              // 处理选项 - 转为JSON字符串
              const cleanOptions = {}
              Object.entries(this.questionForm.options)
                .filter(([_, value]) => value.trim())
                .forEach(([key, value]) => {
                  cleanOptions[key] = value.trim()
                })
              data.options = JSON.stringify(cleanOptions)
            } else {
              // 填空题、简答题和论述题统一使用 analysis 作为答案
              data.answer = this.questionForm.analysis
              data.analysis = this.questionForm.analysis
            }

            // 转换数值型
            data.score = Number(data.score)
            data.sort = Number(data.sort)
            data.testPaperId = Number(data.testPaperId)
            
            if (this.currentId) {
              await updateQuestion(data)
            } else {
              await addQuestion(data)
            }
            
            ElMessage.success(`${this.dialogTitle}成功`)
            this.dialogVisible = false
            this.getList()
          } catch (error) {
            console.error(`${this.dialogTitle}失败:`, error)
            ElMessage.error(`${this.dialogTitle}失败`)
          }
        }
      })
    },

    // 添加选项
    addOption() {
      const options = this.questionForm.options
      const keys = Object.keys(options)
      if (keys.length >= 8) return // 最多8个选项

      // 找到可用的下一个字母
      const alphabet = 'abcdefgh'
      let nextKey = ''
      for (let i = 0; i < alphabet.length; i++) {
        const key = alphabet[i]
        if (!options[key]) {
          nextKey = key
          break
        }
      }

      if (nextKey) {
        this.$set(this.questionForm.options, nextKey, '')
        if (this.questionForm.type === '多选') {
          this.$set(this.questionForm.multiAnswer, nextKey, false)
        }
      }
    },

    // 删除选项
    removeOption(key) {
      const options = { ...this.questionForm.options }
      delete options[key]
      
      // 重新排序选项
      const sortedOptions = {}
      Object.entries(options)
        .sort(([a], [b]) => a.localeCompare(b))
        .forEach(([key, value]) => {
          sortedOptions[key] = value
        })
      
      this.questionForm.options = sortedOptions

      // 处理答案
      if (this.questionForm.type === '单选' && this.questionForm.answer === key.toUpperCase()) {
        this.questionForm.answer = ''
      } else if (this.questionForm.type === '多选') {
        const multiAnswer = { ...this.questionForm.multiAnswer }
        delete multiAnswer[key]
        this.questionForm.multiAnswer = multiAnswer
      }
    },

    // 添加返回方法
    goBack() {
      this.$router.back()
    }
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
}

.option-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.option-item .el-input {
  flex: 1;
}

.option-label {
  width: 30px;
  text-align: right;
}

.option-actions {
  margin-top: 10px;
  padding-left: 30px;
}

.type-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>
